package us.team.openAnAppAtRandom;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    
    private static final int REQUEST_CODE_OVERLAY_PERMISSION = 1001;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 检查悬浮窗权限
        if (checkOverlayPermission()) {
            // 如果已有权限，直接启动遮罩层
            startService(new Intent(this, MaskService.class));
            // 最小化应用
            moveTaskToBack(true);
        }
        
        // 创建线性布局
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        
        // 添加欢迎文本
        TextView tv = new TextView(this);
        tv.setText("黑色遮罩层演示");
        tv.setTextSize(24);
        layout.addView(tv);
        
        // 添加按钮来显示遮罩层
        Button showMaskButton = new Button(this);
        showMaskButton.setText("显示黑色遮罩层");
        showMaskButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查权限并启动遮罩层服务
                if (hasOverlayPermission()) {
                    Intent intent = new Intent(MainActivity.this, MaskService.class);
                    startService(intent);
                    // 最小化应用
                    moveTaskToBack(true);
                } else {
                    Toast.makeText(MainActivity.this, "请先授予悬浮窗权限", Toast.LENGTH_SHORT).show();
                    requestOverlayPermission();
                }
            }
        });
        layout.addView(showMaskButton);
        
        // 添加退出按钮
        Button exitButton = new Button(this);
        exitButton.setText("退出程序");
        exitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 停止服务并退出程序
                stopService(new Intent(MainActivity.this, MaskService.class));
                finish();
                System.exit(0);
            }
        });
        layout.addView(exitButton);
        
        setContentView(layout);
    }
    
    /**
     * Check if overlay permission is granted
     */
    private boolean hasOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return Settings.canDrawOverlays(this);
        }
        return true; // Permission is granted by default on Android < 6.0
    }
    
    /**
     * Check overlay permission and request if not granted
     * @return true if permission is granted, false otherwise
     */
    private boolean checkOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
            Toast.makeText(this, "需要悬浮窗权限来显示遮罩层", Toast.LENGTH_LONG).show();
            requestOverlayPermission();
            return false;
        }
        return true;
    }
    
    /**
     * Request overlay permission
     */
    private void requestOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, REQUEST_CODE_OVERLAY_PERMISSION);
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_OVERLAY_PERMISSION) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(this)) {
                    Toast.makeText(this, "悬浮窗权限已授予", Toast.LENGTH_SHORT).show();
                    // 权限获取后立即启动遮罩层
                    startService(new Intent(this, MaskService.class));
                    // 最小化应用
                    moveTaskToBack(true);
                } else {
                    Toast.makeText(this, "悬浮窗权限被拒绝", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 当应用回到前台时，检查是否需要显示遮罩层
        if (hasOverlayPermission()) {
            startService(new Intent(this, MaskService.class));
        }
    }
}